#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Purpose: SQLAlchemy connection chooser
# Created: 04/28/2009
# $Id $
# Copyright (c) 2008,2009 by University College London
# Authors:
#  --<>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with HydroPlatform for details.

import logging
import os

from enthought.traits.api import HasTraits, Str, Bool, File, Enum, Property, \
     Instance, Any
from enthought.traits.ui.api import View, Item, Group, Label, Handler, \
     EnumEditor
from enthought.traits.ui.menu import OKButton, CancelButton

from hydroplatform.model import database as db
from hydroplatform.ui.session import has_dbsession
from hydroplatform.ui.session import remove_loaded_networks


# TODO : should check if driver is present or not and dynamically update 
# the list
DATABASES = ["sqlite", "postgres", "mysql", "oracle", "sybase", "mssql",
             "maxdb", "informix", "firebird", "access"]

DEFAULT_FILEPATH = os.path.join(os.path.expanduser('~'),'hydroplatform.db')

class DbDialogHandler(Handler):
    '''
    Manages what to do when the user has finished choosing the datasource
    '''
    
    def close(self, info, is_ok):
        '''
        On close, transfer load the db
        '''
        if is_ok:
            context = info.object.thcontext

            try:
                # cleanup old session if any
                if has_dbsession(context):
                    if context.session.dbsession is not None:
                        # remove icons from toolbar and menu
                        nodetype_menu =  context.application.get_nodetype_menu(context)
                        nodetype_menu.cleanup()
                        # remove network from map
                        remove_loaded_networks(context)
                        # cleanup old session
                        context.session.dbsession.close() 
                        print id(context.session.dbsession)
                        # TODO : check if setting object to None is sufficient
                        context.session.dbsession = None
                        context.session.hpnetwork = None
                        context.session.hpproject = None
                dbsession = db.get_session(info.object.dbcon)
                # import pdb; pdb.set_trace()
                # Error here, 'Can't import schema generator'
                # MARK
                context.session.dbsession = dbsession
                print id(context.session.dbsession)
            except Exception, e:
                logging.exception(e)
                print e
                context.mainwindow.RunMessageBox("Connection error", 
                            "Error while connecting to the database :%s\n String : %s" % (e, info.object.dbcon))
        return super(DbDialogHandler, self).close(info, is_ok)
    
class ChooseDbConnection(HasTraits):
    
    thcontext = Any
    is_file  = Bool(True, label="Data is located on:",
                    desc="if loaded from file or from database")
    filename = File(label="File", 
                    value=DEFAULT_FILEPATH, 
                    filter=[u"*.db"], 
                    exists=False)
    dbtype    = Enum(DATABASES[0], DATABASES)
    dburl     = Str(label="Host")
    dbname    = Str(labelr="Name")
    dbuser    = Str(label="Username")
    dbpass    = Str(label="Password")
    dbcon     = Property(Str, label="Connection string", 
            depends_on="is_file,filename,dbtype,dburl,dbname,dbuser,dbpass")

    
    def _get_dbcon(self):
        '''
        '''
        if self.is_file is True:
            return u"sqlite:///%s" % self.filename
        else:
            # TODO : should support existing format for dbcon, see
            # http://www.sqlalchemy.org/docs/05/reference/dialects/index.html
            return u"%s://%s:%s@%s/%s" % (self.dbtype, self.dbuser, 
                                         self.dbpass, self.dburl, self.dbname)
    
    traits_view = View(Item("is_file", 
                            editor=EnumEditor(values={True: "1:My computer",
                                                      False : "2:A server"}),
                            style="custom"),
                       Group(
                           Item("filename", width=400), 
                            enabled_when="is_file is True",
                            #visible_when="is_file is True",
                            label="Database on local computer"
                        ),
                       Group(
                           Item("dbtype"),
                           Item("dburl"),
                           Item("dbname"),
                           Item("dbuser"),
                           Item("dbpass"),
                           enabled_when="is_file is False",
                           #visible_when="is_file is False",
                           label="Database on a server"
                       ),
                       #Label("Connection String"),
                       #Item("dbcon", show_label=False,
                       #     style="readonly"),
                       title="Select Database",
                       buttons = [OKButton, CancelButton],
                       handler=DbDialogHandler())

    
